<template>
    <div class="user-list-container">
        <!-- 页面标题 -->
        <div class="header-title">角色管理</div>

        <!-- 查询与筛选区域 -->
        <el-form :inline="true" class="filter-form" size="small">
            <el-form-item>
                <el-input v-model="search.RoleName" placeholder="职务名称" clearable />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="onSearch">查询</el-button>
                <el-button @click="onReset">重置</el-button>
            </el-form-item>
        </el-form>

        <!-- 操作按钮 -->
        <div class="action-btns" style="margin-bottom: 16px;">
            <el-button type="primary" @click="handleCreateRole">新建职务</el-button>
        </div>

        <!-- 角色数据表格 -->
        <el-table :data="roleList" border stripe style="width: 100%">
            <el-table-column type="selection" width="50" />
            <el-table-column prop="roleName" label="职务名称" width="100" />
            <el-table-column prop="roleStatus" label="状态" width="100">
                <template #default="scope">
                    <span class="status-dot">
                        <span v-if="scope.row.roleStatus == 0">
                            <span class="dot"></span>启用
                        </span>
                        <span v-else>
                            <span class="dot2"></span>禁用
                        </span>
                    </span>
                </template>
            </el-table-column>
            <el-table-column prop="memberCount" label="成员数量" width="100">
                <template #default="scope">
                    <span class="member-count" style="color: blue;">{{ scope.row.memberCount }}</span>
                </template>
            </el-table-column>
            <el-table-column prop="departmentDescription" label="部门描述" />
            <el-table-column prop="createTime" label="更新时间" width="180">
                <template #default="scope">
                    {{ moment(scope.row.createTime).format("YYYY-MM-DD HH:mm:ss") }}
                </template>
            </el-table-column>
            <el-table-column label="操作">
                <template #default="scope">
                    <el-button size="small" plain type="primary"
                        @click="handleSetPermissions(scope.row)">设置权限</el-button>
                    <el-button size="small" plain type="primary" @click="handleEditRole(scope.row)">编辑职务</el-button>
                    <el-button size="small" plain type="primary" @click="handleCreateRole()">添加人员</el-button>
                    <el-button size="small" plain type="primary" @click="handleSetStatus(scope.row)">设置状态</el-button>
                    <el-button size="small" plain type="primary" @click="handleCreateRole()">复制</el-button>
                    <el-button size="small" plain type="danger" @click="handleDeleteRole(scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 设置状态模态框 -->
        <el-dialog title="设置状态" v-model="statusDialogVisible" width="30%">
            <!-- 模态框内容 -->
            <el-form :model="statusForm" :rules="statusRules" ref="statusFormRef" label-width="100px">
                <el-form-item label="选择状态:" prop="RoleStatus" required>
                    <el-radio-group v-model="statusForm.RoleStatus">
                        <el-radio-button :label="0">启用</el-radio-button>
                        <el-radio-button :label="1">禁用</el-radio-button>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="备注内容:" prop="ContentDesc" required>
                    <el-input type="textarea" v-model="statusForm.ContentDesc" placeholder="请输入内容" maxlength="100"
                        show-word-limit :rows="4"></el-input>
                </el-form-item>
            </el-form>

            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="statusDialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="saveStatus">保存</el-button>
                </span>
            </template>
        </el-dialog>

        <!-- 新建职务模态框 -->
        <el-dialog title="新建职务" v-model="AddDialogVisible" width="30%">
            <!-- 模态框内容 -->
            <el-form :model="AddForm" :rules="AddRules" ref="AddFormRef" label-width="100px">
                <el-form-item label="职务名称:" prop="roleName">
                    <el-input v-model="AddForm.roleName" placeholder="请输入名称" />
                </el-form-item>
                <el-form-item label="职务描述:" prop="departmentDescription" required>
                    <el-input type="textarea" v-model="AddForm.departmentDescription" placeholder="请输入内容"
                        maxlength="100" show-word-limit :rows="4"></el-input>
                </el-form-item>
            </el-form>

            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="AddDialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="saveAdd">保存</el-button>
                </span>
            </template>
        </el-dialog>

        <!-- 编辑职务模态框 -->
        <el-dialog title="编辑职务" v-model="updateDialogVisible" width="30%" @close="resetupdateDialog">
            <!-- 模态框内容 -->
            <el-form :model="UpdateForm" :rules="UpdateRules" ref="updateFormRef" label-width="100px">
                <el-form-item label="职务名称:" prop="RoleName">
                    <el-input v-model="UpdateForm.RoleName" placeholder="请输入名称" />
                </el-form-item>
                <el-form-item label="职务描述:" prop="DepartmentDescription" required>
                    <el-input type="textarea" v-model="UpdateForm.DepartmentDescription" placeholder="请输入内容"
                        maxlength="100" show-word-limit :rows="4"></el-input>
                </el-form-item>
            </el-form>

            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="updateDialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="saveupdate">保存</el-button>
                </span>
            </template>
        </el-dialog>

    </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { GetRole, DeleteRole, UpdateRoleStatus, UpdateRoleZhiW ,AddRoleZhiW} from '@/Api/role';
import moment from 'moment';
import type { FormInstance, FormRules } from 'element-plus';
import router from '@/router';
import { lo } from 'element-plus/es/locales.mjs';

// 查询条件
const search = reactive({
    RoleName: '',
});

// 角色列表数据
const roleList = ref([])

// 控制设置状态对话框的显示隐藏
const statusDialogVisible = ref(false);

// 控制新建职务对话框的显示隐藏
const AddDialogVisible = ref(false);

// 控制编辑职务对话框的显示隐藏
const updateDialogVisible = ref(false);

// 设置状态表单ref
const statusFormRef = ref<FormInstance>();

// 设置状态表单
const statusForm = reactive({
    RoleId: null, // 添加角色ID字段
    RoleStatus: 1, // 默认启用
    ContentDesc: '',
});

// 设置状态表单校验
const statusRules = reactive<FormRules>({
    status: [{ required: true, message: '请选择状态', trigger: 'change' }],
    ContentDesc: [
        { required: true, message: '请输入备注内容', trigger: 'blur' },
        { max: 100, message: '备注内容不能超过100个字符', trigger: 'blur' },
    ],
});


// 新建职务表单ref
const AddFormRef = ref<FormInstance>();

// 新建职务表单
const AddForm = reactive({
    roleName: '',
    departmentDescription: '',
});

// 新建职务表单校验
const AddRules = reactive<FormRules>({
    roleName: [{ required: true, message: '请输入职务名称', trigger: 'change' }],
    departmentDescription: [
        { required: true, message: '请输入职务描述', trigger: 'blur' },
        { max: 100, message: '备注内容不能超过100个字符', trigger: 'blur' },
    ],
});

// 编辑职务表单ref
const updateFormRef = ref<FormInstance>();

// 编辑职务表单
const UpdateForm = reactive({
    Roleid: null, // 角色ID
    RoleName: '',
    DepartmentDescription: '',
});

// 编辑职务表单校验
const UpdateRules = reactive<FormRules>({
    RoleName: [{ required: true, message: '请输入职务名称', trigger: 'change' }],
    DepartmentDescription: [
        { required: true, message: '请输入职务描述', trigger: 'blur' },
        { max: 100, message: '备注内容不能超过100个字符', trigger: 'blur' },
    ],
});

// 查询方法
const onSearch = async () => {
    var parmars = {
        RoleName: search.RoleName,
    };
    const reponse = await GetRole(parmars);
    roleList.value = reponse.data.data;
};

// 重置方法
const onReset = () => {
    search.RoleName = '';
    onSearch(); // 重置后重新查询
};

// 处理新建职务
const handleCreateRole = () => {
     AddDialogVisible.value = true
     AddForm.roleName='',
     AddForm.departmentDescription=''
};

// 处理设置权限
const handleSetPermissions = (row:any) => {
    router.push({ path: '/permissionlist'});
    localStorage.setItem('roleId',row.id);
    localStorage.setItem('roleName',row.roleName);
localStorage.setItem('roleStatus',row.roleStatus);
localStorage.setItem('departmentDescription',row.departmentDescription);
};

// 处理编辑职务
const handleEditRole = (row: any) => {
    updateDialogVisible.value = true
    UpdateForm.Roleid = row.id,
        UpdateForm.RoleName = row.roleName;
    UpdateForm.DepartmentDescription = row.departmentDescription;
};


// 关闭设置状态对话框时重置表单和校验状态
const resetupdateDialog = () => {
    UpdateForm.Roleid = null;
    UpdateForm.RoleName = '';
    UpdateForm.DepartmentDescription = '';
    if (updateFormRef.value) {
        updateFormRef.value.resetFields();
    }
};


// 新建职务设置
const saveAdd = async () => {
    if (!AddFormRef.value) return;
    await AddFormRef.value.validate(async (valid) => {
        if (valid) {
            //调用接口新建职务
            const reponse = await AddRoleZhiW(AddForm);
            if (reponse.data.code == 200) {
                ElMessage.success("编辑职务成功");
                AddDialogVisible.value = false; // 关闭对话框
                onSearch(); // 刷新列表
            } else {
                ElMessage.error("编辑职务失败");
            }


        } else {
            console.log('表单校验失败');
        }
    });
};

// 编辑职务设置
const saveupdate = async () => {
    if (!updateFormRef.value) return;
    await updateFormRef.value.validate(async (valid) => {
        if (valid) {
            //调用接口编辑职务
            const params = {
                Roleid: UpdateForm.Roleid,
                RoleName: UpdateForm.RoleName,
                DepartmentDescription: UpdateForm.DepartmentDescription
            };
            const reponse = await UpdateRoleZhiW(params);
            if (reponse.data.code == 200) {
                ElMessage.success("编辑职务成功");
                updateDialogVisible.value = false; // 关闭对话框
                onSearch(); // 刷新列表
            } else {
                ElMessage.error("编辑职务失败");
            }


        } else {
            console.log('表单校验失败');
        }
    });
};


// 处理删除
const handleDeleteRole = (row: any) => {
    //调用接口删除角色
    ElMessageBox.confirm('确定删除该角色吗?',
        '提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(async () => {
        const reponse = await DeleteRole(row.id);
        if (reponse.data.code == 200) {
            ElMessage.success('删除成功');
            onSearch();
        } else {
            ElMessage.error('删除失败');
        }
    })
};

// 处理设置状态
const handleSetStatus = (row: any) => {
    // 填充表单数据
    statusForm.RoleId = row.id;
    statusForm.RoleStatus = row.roleStatus;
    statusForm.ContentDesc = ''; // 清空备注
    statusDialogVisible.value = true; // 打开对话框
};

// 关闭设置状态对话框时重置表单和校验状态
const resetStatusDialog = () => {
    statusForm.RoleId = null;
    statusForm.RoleStatus = 1;
    statusForm.ContentDesc = '';
    if (statusFormRef.value) {
        statusFormRef.value.resetFields();
    }
};

// 保存状态设置
const saveStatus = async () => {
    if (!statusFormRef.value) return;
    await statusFormRef.value.validate(async (valid) => {
        if (valid) {
            console.log('保存状态:', statusForm);
            //调用接口更新角色状态和备注
            const params = {
                RoleId: statusForm.RoleId,
                RoleStatus: statusForm.RoleStatus,
                ContentDesc: statusForm.ContentDesc,
            };
            const reponse = await UpdateRoleStatus(params);
            if (reponse.data.code == 200) {
                ElMessage.success("状态更新成功");
                statusDialogVisible.value = false; // 关闭对话框
                onSearch(); // 刷新列表
            } else {
                ElMessage.error("状态更新失败");
            }


        } else {
            console.log('表单校验失败');
        }
    });
};

//文档就绪
onMounted(() => {
    onSearch();
})

</script>

<style scoped>
.user-list-container {
    background: #fff;
    padding: 2% 3%;
    border-radius: 0.5em;
}

.header-title {
    font-size: 1.3em;
    font-weight: bold;
    margin-bottom: 2%;
}

.filter-form {
    margin-bottom: 1.5%;
}

.action-btns {
    margin-bottom: 1.5%;
}

.status-dot {
    display: flex;
    align-items: center;
    font-size: 15px;
}

.status-dot .dot {
    width: 8px;
    height: 8px;
    background: #13ce66;
    /* 启用状态的绿色 */
    border-radius: 50%;
    display: inline-block;
    margin-right: 6px;
}

.status-dot .dot2 {
    width: 8px;
    height: 8px;
    background: red;
    /* 禁用状态的红色 */
    border-radius: 50%;
    display: inline-block;
    margin-right: 6px;
}

/* 可以根据需要调整表格单元格的padding */
.el-table .el-table__cell {
    padding: 6px 8px !important;
    font-size: 14px;
}
</style>
